#include "OpenGLShapeSphere.h"
#include<gl/GL.h>
#include<vector>
#include<gl/GLU.h>

unsigned int VBO, VAO, EBO;
const unsigned int SCR_WIDTH = 1200;
const unsigned int SCR_HEIGHT = 1200;
const GLfloat  PI = 3.14159265358979323846f;
//将球横纵划分成50X50的网格
const int Y_SEGMENTS = 10;
const int X_SEGMENTS = 10;

bool ShapeSphere::init(QOpenGLFunctions_3_3_Core* f)
{
	m_f = f;

	// 生成球的顶点
	for (int y = 0; y <= Y_SEGMENTS; y++)
	{
		for (int x = 0; x <= X_SEGMENTS; x++)
		{
			float xSegment = (float)x / (float)X_SEGMENTS;
			float ySegment = (float)y / (float)Y_SEGMENTS;
			float xPos = std::cos(xSegment * 2.0f * PI) * std::sin(ySegment * PI);
			float yPos = std::cos(ySegment * PI);
			float zPos = std::sin(xSegment * 2.0f * PI) * std::sin(ySegment * PI);

			sphereVertices.push_back(xPos);
			sphereVertices.push_back(yPos);
			sphereVertices.push_back(zPos);
		}
	}

	// 生成球的Indices
	for (int i = 0; i < Y_SEGMENTS; i++)
	{
		for (int j = 0; j < X_SEGMENTS; j++)
		{
			sphereIndices.push_back(i * (X_SEGMENTS + 1) + j);
			sphereIndices.push_back((i + 1) * (X_SEGMENTS + 1) + j);
			sphereIndices.push_back((i + 1) * (X_SEGMENTS + 1) + j + 1);

			sphereIndices.push_back(i * (X_SEGMENTS + 1) + j);
			sphereIndices.push_back((i + 1) * (X_SEGMENTS + 1) + j + 1);
			sphereIndices.push_back(i * (X_SEGMENTS + 1) + j + 1);
		}
	}

	//————————————————

	//	版权声明：本文为博主原创文章，遵循 CC 4.0 BY - SA 版权协议，转载请附上原文出处链接和本声明。

	//	原文链接：https ://blog.csdn.net/qq_51684393/article/details/129801437

	return false;
}

bool ShapeSphere::render()
{
	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	glEnableClientState(GL_VERTEX_ARRAY);
	glEnableClientState(GL_NORMAL_ARRAY);
	glColor3f(1.0,0,0);
	glVertexPointer(3, GL_FLOAT, 0, sphereVertices.data());
	glNormalPointer(GL_FLOAT, 0, sphereVertices.data());
	glDrawElements(GL_TRIANGLES, X_SEGMENTS * Y_SEGMENTS * 6, GL_UNSIGNED_INT, sphereIndices.data());
	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_NORMAL_ARRAY);
	//m_f->glBindVertexArray(0);
	//————————————————
	//	版权声明：本文为博主原创文章，遵循 CC 4.0 BY - SA 版权协议，转载请附上原文出处链接和本声明。
	//	原文链接：https ://blog.csdn.net/qq_51684393/article/details/129801437
	return false;
}

bool ShapeSphere::release()
{
	return false;
}
